<template>
  <el-button type="success"  @click="dialogFormVisible = true">新增</el-button>
  <el-button type="primary" @click="search((showMessage = true))">查询</el-button>
  <el-table
    :data="tableData"
    height="550"
    stripe
    border
    :table-layout="fixed"
    style="width: 100%;"
  >
    <el-table-column prop="tableNo" label="编号" />

    <el-table-column label="名称">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.row.name }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.name }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="unitPrice" label="单价（元/时）" > 
      <template #default="scope">
        {{ scope.row.unitPrice +  "元 / 时"}}
      </template>
    </el-table-column>
    <el-table-column prop="status" label="状态">
      <template #default="scope">
        {{ scope.row.status === 0 ? "空闲" : "使用中" }}
      </template>
    </el-table-column>
    <el-table-column prop="remark" label="备注">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.row.remark }}</div>
          </template>
          <template #reference>
            {{ scope.row.remark }}
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间">
      <template #default="scope">
        {{ utils.formatDate(scope.row.createTime) }}
      </template>
    </el-table-column>
    <el-table-column prop="updateTime" label="更新时间">
      <template #default="scope">
        {{ utils.formatDate(scope.row.updateTime) }}
      </template>
    </el-table-column>

    <el-table-column fixed="right" width="150" label="操作">
      <template #default="scope">
        <el-button size="small" type="primary" plain @click="edit(scope.$index, scope.row)"
          >修改</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="remove(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="pagination-block">
    <el-pagination
      background
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      prev-text="上一页"
      next-text="下一页"
      :disabled="disabled"
      :background="background"
      layout="prev, pager, next, sizes, jumper,total,slot"
      v-model:total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </div>

  <el-dialog v-model="dialogFormVisible" destroy-on-close title="牌桌管理">
    <el-form ref="formRef" :model="form">
      <el-form-item
        label="编号"
        :label-width="formLabelWidth"
        :rules="[{ required: true, message: '编号必填' }]"
      >
        <el-input
          v-model="form.tableNo"
          maxlength="10"
          placeholder="请输入唯一编号"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="名称" :label-width="formLabelWidth">
        <el-input
          v-model="form.name"
          maxlength="128"
          placeholder="请输入名称"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="单价(元/时）" :label-width="formLabelWidth">
        <el-input-number
          type="number"
          v-model="form.unitPrice"
          min="0"
          maxlength="10"
          placeholder="请输入单价"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="备注" :label-width="formLabelWidth">
        <el-input
          type="textarea"
          :rows="3"
          maxlength="300"
          placeholder="请输入备注"
          v-model="form.remark"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="id" :label-width="formLabelWidth" v-show="false">
        <el-input v-model="form.idBoardGameTable" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrUpdate"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { Timer } from "@element-plus/icons-vue";
import { dbConnect } from "@/utils/sqlUtils.js";
import { reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as utils from "@/utils/utils.js";

const dialogFormVisible = ref(false);
const tableData = reactive([]);
const formLabelWidth = "140px";
const formRef = ref({});
const total = ref(0);
const pageNo = ref(1);
const pageSize = ref(10);

const form = reactive({
  idBoardGameTable: "",
  tableNo: "",
  name: "",
  remark: "",
  unitPrice: 0,
  createTime: {},
  updateTime: {},
});

resetTotal();

search();

function resetTotal() {
  dbConnect.all(
    "select count(1) as count from board_game_table",
    (err, row) => {
      total.value = row[0].count;
    }
  );
}


function handleSizeChange(pageSize) {
  search();
}

function handleCurrentChange(pageNo) {
  search();
}

function edit(index, row) {
  form.name = row.name;
  form.idBoardGameTable = row.idBoardGameTable;
  form.tableNo = row.tableNo;
  form.unitPrice = row.unitPrice;
  form.remark = row.remark;
  dialogFormVisible.value = true;
}

function saveOrUpdate() {
  if (utils.isNotEmpty(form.idBoardGameTable)) {
    let updateSql = `UPDATE board_game_table SET tableNo=?, name=?, unitPrice=?, remark=?, updateTime=? WHERE idBoardGameTable = ?`;
    dbConnect
      .prepare(updateSql, [
        form.tableNo,
        form.name,
        form.unitPrice,
        form.remark,
        new Date().getTime(),
        form.idBoardGameTable,
      ])
      .run((err) => {
        if (err == null) {
          ElMessage({
            showClose: true,
            message: "修改成功",
            type: "success",
          });
          dialogFormVisible.value = false;
          search();
        } else {
          ElMessage({
            showClose: true,
            message: "修改失败"+ err,
            type: "error" ,
          });
        }
      });
    form.name = null;
    form.unitPrice = null;
    form.remark = null;
    form.tableNo = null;
    form.idBoardGameTable = null;
    return;
  }


  let insertsql = `INSERT INTO board_game_table (tableNo,name,unitPrice,remark,updateTime,createTime) VALUES (?, ?,?,?,?,?);`;
  dbConnect
    .prepare(insertsql, [
      form.tableNo,
      form.name,
      form.unitPrice,
      form.remark,
      new Date().getTime(),
      new Date().getTime(),
    ])
    .run((err) => {
      if (err == null) {
        ElMessage({
          showClose: true,
          message: "新增成功",
          type: "success",
        });
        dialogFormVisible.value = false;
        search();
      } else {
        ElMessage({
          showClose: true,
          message: "新增失败" + err,
          type: "error",
        });
      }
      form.name = null;
        form.unitPrice = null;
        form.remark = null;
        form.tableNo = null;
        form.idBoardGameTable = null;
    });
}

function search(showMessage) {
  resetTotal();
  dbConnect.all(
    "select * from board_game_table LIMIT " +
      pageSize.value +
      " OFFSET " +
      (pageNo.value - 1) * pageSize.value,
    function (err, row) {
      if (utils.isNotEmpty(err)) {
        ElMessage({
          type: "error",
          message: "查询失败" + err,
        });
      } else {
        if (showMessage) {
          ElMessage({ type: "success", message: "查询成功" });
        }
        tableData.splice(0);
        tableData.push(...row);
      }
    }
  );
}

function remove(index, row) {
  ElMessageBox.confirm("是否删除该数据", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let removeSql = `DELETE FROM board_game_table WHERE idBoardGameTable = ?`;
      dbConnect.prepare(removeSql, [row.idBoardGameTable]).run(() => {
        ElMessage({
          type: "success",
          message: "删除完成",
        });
        search();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      });
    });
}
</script>


<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}

.pagination-block {
  margin-top: 10px;
}
</style>